package com.chalk.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.chalk.config.task.DynamicJob;
import com.chalk.dao.TaskJobDao;
import com.chalk.model.TaskJob;
import com.chalk.service.TaskJobService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 系统定时任务表(TaskJob)表服务实现类
 *
 * @author maxiaoqiang
 * @since 2019-03-28 09:54:29
 */
@Service
public class TaskJobServiceImpl extends ServiceImpl<TaskJobDao, TaskJob> implements TaskJobService {

    @Autowired
    private TaskJobDao taskJobDao;

    /*自定义接口*/

    /**
     * 根据主键批量(逻辑)删除
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteBatchByPrimaryKey(String[] ids) {
        return taskJobDao.deleteBatchByPrimaryKey(ids);
    }


    //获取JobDataMap.(Job参数对象)
    @Override
    public JobDataMap getJobDataMap(TaskJob job) {
        JobDataMap map = new JobDataMap();
        map.put("jobName", job.getJobName());
        map.put("jobClassName", job.getJobClassName());
        map.put("timerRule", job.getTimerRule());
        map.put("jobDescription", job.getJobDescription());
        return map;
    }

    //获取JobDetail,JobDetail是任务的定义,而Job是任务的执行逻辑,JobDetail里会引用一个Job Class来定义
    @Override
    public JobDetail geJobDetail(JobKey jobKey, String description, JobDataMap map) {
        return JobBuilder.newJob(DynamicJob.class)
                .withIdentity(jobKey)
                .withDescription(description)
                .setJobData(map)
                .storeDurably()
                .build();
    }

    //获取Trigger (Job的触发器,执行规则)
    @Override
    public Trigger getTrigger(TaskJob job) {
        return TriggerBuilder.newTrigger()
                .withIdentity(job.getJobName(), job.getJobClassName())
                .withSchedule(CronScheduleBuilder.cronSchedule(job.getTimerRule()))
                .build();
    }

    //获取JobKey,包含Name和Group
    @Override
    public JobKey getJobKey(TaskJob job) {
        return JobKey.jobKey(job.getJobName(), job.getJobClassName());
    }
}